package cn.edu.nju.testdb.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class BaseDao {
	public static final String DRIVER="com.microsoft.jdbc.sqlserver.SQLServerDriver";
	public static final String URL="jdbc:microsoft:sqlserver://localhost:1433;DataBaseName=db";
	//public static final String DRIVER="com.mysql.jdbc.Driver";
	//public static final String URL="jdbc:mysql://localhost:3306/db";
	public static final String DBNAME="sa";
	public static final String DBPASS="sa";
	
	public Connection getConn(){
		Connection conn=null;
		try {
			Class.forName(DRIVER);
			conn=DriverManager.getConnection(URL, DBNAME, DBPASS); 
		} catch (Exception e) {
			e.printStackTrace();
		}
		return conn;
		
	}
	public void closeAll(Connection conn, PreparedStatement pstmt,ResultSet rs) {
		if(rs!=null) {
			try {
				rs.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if(pstmt!=null) {
			try {
				pstmt.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if(conn!=null) {
			try {
				conn.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	public int executeSQL(String sql,String []getValue) {
		Connection conn=null;
		PreparedStatement pstmt=null;
		int num=0;
		try {
			conn=getConn();
			pstmt=conn.prepareStatement(sql);
			if(getValue!=null) {
				for (int i = 0; i < getValue.length; i++) {
					pstmt.setString(i+1, getValue[i]);
					
				}
			}
			num=pstmt.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			closeAll(conn,pstmt,null);
		}
		return num;
	}
}
